<template>
  <div class="intermediate-inspection-container">
    <div class="search" v-if="showSearch">
      <SearchBar ref="searchBarRef" :components="conditionComponents" :hideRightArea="false" @search="refreshTableData" />
    </div>
    <div class="list">
      <TableForm ref="tableRef" :data="dataList" :columns="columns" :tableLoading="loading" :total-count="total"
        v-model:showSearch="showSearch" :showRowSelection="true" :showPagination="true" :showToolBar="true"
        @refresh="refreshTableData" :download="(params) => { exportListData(params)}" :right-first-btn-permission="exportBtnPermission">
        <template #leftMenu>
          <el-button v-if="projectNature === 1" type="primary" @click="handleBatchStart" v-hasPermi="['project:portrait:portraitIntermediateInspection:startMidInspection']">开启中检</el-button>
          <el-button v-else-if="projectNature === 2" type="primary" @click="handleBatchStart" v-hasPermi="['project:portrait:portraitIntermediateInspection:startMidInspection']">开启中检</el-button>
        </template>
        <template #statusName="{ record }">
          <div class="flex items-center space-x-[8px]">
            <span class="h-[6px] w-[6px] rounded-[3px]"
              :style="{ backgroundColor: intermediateInspectionStatusBgColorMap[record.status as keyof typeof intermediateInspectionStatusBgColorMap] }" />
            <span
              :style="{ color: intermediateInspectionStatusBgColorMap[record.status as keyof typeof intermediateInspectionStatusBgColorMap] }">{{
                record.statusName }}</span>
          </div>
        </template>
        <!-- 纵项 -->
        <template #default="{ record }" v-if="projectNature === 1">
          <el-button link type="primary" @click="handleDetail(record.id, record.projectName)" v-hasPermi="['project:portrait:portraitIntermediateInspection:view']">查看</el-button>
          <el-button v-if="record.status === 3" link type="primary" @click="handleStart([record.id])" v-hasPermi="['project:portrait:portraitIntermediateInspection:startMidInspectionList']">开启中检</el-button>
          <el-button v-if="record.status === 7" link type="primary"
            @click="handleAudit(record.id, record.projectName)" v-hasPermi="['project:portrait:portraitIntermediateInspection:midInspectionAudit']">中检审核</el-button>
          <el-button link type="primary" @click="handleAuditRecord(record.id)" v-hasPermi="['project:portrait:portraitIntermediateInspection:auditRecord']">审核记录</el-button>
        </template>
        <!-- 校级 -->
        <template #default="{ record }" v-else-if="projectNature === 2">
          <el-button link type="primary" @click="handleDetail(record.id, record.projectName)" v-hasPermi="['project:school:schoolIntermediateInspection:view']">查看</el-button>
          <el-button v-if="record.status === 3" link type="primary" @click="handleStart([record.id])" v-hasPermi="['project:school:schoolIntermediateInspection:startMidInspectionList']">开启中检</el-button>
          <el-button v-if="record.status === 7" link type="primary"
            @click="handleAudit(record.id, record.projectName)" v-hasPermi="['project:school:schoolIntermediateInspection:midInspectionAudit']">中检审核</el-button>
          <el-button link type="primary" @click="handleAuditRecord(record.id)" v-hasPermi="['project:school:schoolIntermediateInspection:auditRecord']">审核记录</el-button>
        </template>
      </TableForm>
      <AuditRecordDrawer v-model:visible="auditRecordVisible" :project-id="projectId" v-if="auditRecordVisible" />

      <DelConfirmModal v-if="startVisible" :visible="startVisible" ok-text="确定" ok-type="primary"
        :loading="startLoading" text="是否确认开启项目的中期检查?" @cancel="startVisible = false"
        @ok="approveInitiate({ projectIds: projectIds, type: 3 })" />
    </div>
  </div>
</template>

<script setup lang="ts" name="Index">
import { exportProjectListApi, getProjectPageApi, submitApproveInitiateApi } from '@/api/project'
import { BaseSuccessRespDTO } from '@/api/project/types';
import { ProjectBasePageVO, PageBeanProjectBasePageVO } from '@/types/project/response';
import { dictEnum, projectNatureEnum } from '@/utils/constEnum';
import { intermediateInspectionStatusBgColorMap } from '@/utils/constText';
import formateDate from '@/utils/formateDate';
import AuditRecordDrawer from '@/components/AuditRecordDrawer/index.vue'
import { downloadFile } from '@/utils/download';

const { proxy } = getCurrentInstance()

const dict = proxy.useDict(
  dictEnum.department,
  dictEnum.verticalProject,
  dictEnum.schoolProjectSort,
  dictEnum.projectType,
  dictEnum.projectLevel
)

const route = useRoute()
const router = useRouter()

// 1：纵向项目  2：校级项目  3：横向项目
const projectNature = computed(() => {
  return Number(route.query.projectNature)
})

// 导出按钮权限
const exportBtnPermission = computed(() => {
  switch(projectNature.value) {
    // 1纵向
    case projectNatureEnum.projectNaturePortrait:
      return ['project:portrait:portraitIntermediateInspection:export']
    // 2校级
    case projectNatureEnum.projectNatureSchool:
      return ['project:school:schoolIntermediateInspection:export']
    default:
      return
  }
})

const searchBarRef = ref()
const showSearch = ref(true)
// 请求参数
const parameters = ref({
  page: 1,
  size: 20,
  department: '',
  projectType: '',
  projectCategory: '',
  projectLevel: '',
  managerName: '',
  projectName: '',
  status: [],
  dateArray: []
})

const defaultStatus = [3, 6, 7, 8, 9]

const conditionComponents = computed(() => [
  {
    type: 1,
    key: 'projectType',
    placeholder: '项目分类',
    config: {
      options: projectNature.value === 1 ? dict[dictEnum.verticalProject] : dict[dictEnum.schoolProjectSort]
    }
  },
  {
    type: 1,
    key: 'projectCategory',
    placeholder: '项目类别',
    config: {
      options: dict[dictEnum.projectType]
    }
  },
  {
    type: 1,
    key: 'department',
    placeholder: '所属院系（部）',
    config: {
      options: dict[dictEnum.department]
    }
  },
  {
    type: 1,
    key: 'projectLevel',
    placeholder: '项目级别',
    config: {
      options: dict[dictEnum.projectLevel]
    }
  },
  {
    type: 2,
    key: 'dateArray',
    width: '460px',
    config: {
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
    }
  },
  {
    type: 1,
    key: 'status',
    placeholder: '项目状态',
    config: {
      multiple: true,
      options: [
        { title: '已立项', value: 3 },
        { title: '中检待提交', value: 6 },
        { title: '中检待审核', value: 7 },
        { title: '中检通过', value: 8 },
        { title: '中检未通过', value: 9 },
      ]
    }
  },
  {
    type: 0,
    key: 'managerName',
    placeholder: '请输入负责人',
  },
  {
    type: 0,
    key: 'projectName',
    placeholder: '请输入项目名称',
  }
])

const tableRef = ref()
const total = ref(0)
const dataList = ref<ProjectBasePageVO[]>([])
const columns = ref([
  {
    title: '序号',
    width: 48,
    dataIndex: 'index',
    formatter: (row: any, column: any, cellValue: any, index: number) => {
      return index + 1
    }
  },
  {
    title: '项目编号',
    minWidth: 60,
    dataIndex: 'projectCode',
  },
  {
    title: '项目名称',
    minWidth: 240,
    dataIndex: 'projectName',
  },
  {
    title: '负责人',
    minWidth: 60,
    dataIndex: 'managerName',
  },
  {
    title: '团队成员',
    minWidth: 80,
    dataIndex: 'teamMember',
  },
  {
    title: '项目分类',
    minWidth: 80,
    dataIndex: 'projectTypeName',
  },
  {
    title: '项目类别',
    minWidth: 80,
    dataIndex: 'projectCategoryName',
  },
  {
    title: '所属院系（部）',
    minWidth: 80,
    dataIndex: 'departmentName',
  },
  {
    title: '起止时间',
    minWidth: 100,
    dataIndex: 'approvalTime',
    formatter: (row) => `${formateDate(row.approvalTime).format('YYYY-MM-DD')}~${formateDate(row.conclusionTime).format('YYYY-MM-DD')}`
  },
  {
    title: '项目经费',
    minWidth: 60,
    dataIndex: 'projectFunding',
  },
  {
    title: '项目级别',
    minWidth: 80,
    dataIndex: 'projectLevelName',
  },
  {
    title: '项目状态',
    minWidth: 80,
    dataIndex: 'statusName',
    slotName: 'statusName',
  },
  {
    title: '操作',
    minWidth: 140,
    dataIndex: 'default',
    slotName: 'default',
  }
])

const projectIds = ref<string[]>([])
const projectId = ref('')
const startVisible = ref(false)
const auditRecordVisible = ref(false)

const { run: getData, loading } = useRequest(getProjectPageApi, {
  manual: true,
  onSuccess: (res: PageBeanProjectBasePageVO) => {
    const { content, totalElements } = res || {}
    dataList.value = content || []
    total.value = totalElements || 0
  }
})

const { run: approveInitiate, loading: startLoading } = useRequest(submitApproveInitiateApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res?.isSuccess) {
      startVisible.value = false
      projectIds.value = []
      ElMessage({
        message: '开启成功!',
        type: 'success',
        plain: true,
      })
      tableRef.value?.refreshInitPage()
    }
  }
})

/* 导出列表数据 */
const { runAsync: exportFile } = useRequest(exportProjectListApi, {
  manual: true,
})

// 导出
const exportListData = async (params) => {
  const data = {
    idList: [...params],
    projectNature: projectNature.value,
  }
  if(!params?.length) {
    data.status = parameters.value.status?.length > 0 ? parameters.value.status : defaultStatus
  }
  const res = await exportFile({
    ...data,
    ...searchBarRef.value.params,
    status: parameters.value.status?.length > 0 ? parameters.value.status : defaultStatus,
    approvalTime: parameters.value.dateArray?.[0],
    conclusionTime: parameters.value.dateArray?.[1]
  })
  downloadFile(res)
}

const refreshTableData = (params) => {
  parameters.value = { ...parameters.value, ...params }
  getData({
    ...parameters.value,
    projectNature: projectNature.value,
    department: parameters.value.department,
    projectType: parameters.value.projectType,
    projectCategory: parameters.value.projectCategory,
    projectLevel: parameters.value.projectLevel,
    managerName: parameters.value.managerName,
    projectName: parameters.value.projectName,
    status: parameters.value.status?.length > 0 ? parameters.value.status : defaultStatus,
    approvalTime: parameters.value.dateArray?.[0],
    conclusionTime: parameters.value.dateArray?.[1]
  })
}

const handleBatchStart = () => {
  if (!tableRef.value?.selectedRowKeys?.length) {
    ElMessage({
      message: '请勾选要开启中检的数据!',
      type: 'warning',
      plain: true,
    })
    return
  }
  projectIds.value = tableRef.value?.selectedRowKeys
  startVisible.value = true
}

const handleStart = (ids: string[]) => {
  projectIds.value = ids
  startVisible.value = true
}

const handleDetail = (id: string, name: string) => {
  router.push({ path: '/project/mine/edit', query: { projectNature: projectNature.value, projectId: id, mode: 'view', projectName: name } })
}

const handleAudit = (id: string, name: string) => {
  router.push({ path: '/project/intermediateInspection/intermediateInspectionReview', query: { projectId: id, projectName: name } })
}

const handleAuditRecord = (id: string) => {
  projectId.value = id
  auditRecordVisible.value = true
}

onMounted(() => {
  tableRef.value?.refreshInitPage()
})
</script>


<style scoped lang="scss">
.intermediate-inspection-container {
  --at-apply: flex flex-col space-y-[16px] h-full;

  .search {
    --at-apply: px-[20px] py-[16px] bg-white rounded-[4px];
  }

  .list {
    --at-apply: flex-1 px-[20px] pb-[20px] bg-white rounded-[4px];
  }
}
</style>